package net.lee.shiro.demo.realm;

import net.lee.shiro.demo.config.shiro.RetryLimitHashedCredentialsMatcher;
import net.lee.shiro.demo.entity.usersystem.SystemUserEntity;
import net.lee.shiro.demo.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Create by lishijun on 2018/4/11
 * Company: lianzhong
 * Domain:  ourgame.com
 * Department:Web Developer
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    IUserService userService;

    public  UserRealm(RetryLimitHashedCredentialsMatcher  credentialsMatcher)
    {
          this.setCredentialsMatcher(credentialsMatcher);
    }

    /**
     * 定义权限验证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userAccount = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //设置用户的角色信息，可以根据角色进行权限验证
        authorizationInfo.setRoles(null);
        //设置用户的权限信息，可以根据权限进行权限验证
        authorizationInfo.setStringPermissions(null);
        return authorizationInfo;
    }

    /**
     * 定义用户身份验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName =(String) authenticationToken.getPrincipal();
        List<SystemUserEntity> userEntityList = userService.getUserByAccount(userName);
        if(userEntityList==null || userEntityList.size()==0)
        {
            throw  new UnknownAccountException();
        }
        SystemUserEntity userEntity = userEntityList.get(0);

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userEntity.getEmail(),userEntity.getPassword(),ByteSource.Util.bytes(userEntity.getCredentialsSalt()),"");

        return authenticationInfo;
    }
}
